/**
 * @description: 这是Eirudy创建的类~
 * @author: Eirudy
 * @hope: 憧憬成为java大师
 **/

package org.eirudy.shareimage.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.eirudy.shareimage.annotation.AuthCheck;
import org.eirudy.shareimage.exception.BusinessException;
import org.eirudy.shareimage.exception.ErrorCode;
import org.eirudy.shareimage.model.entity.User;
import org.eirudy.shareimage.model.enums.UserRoleEnum;
import org.eirudy.shareimage.service.UserService;
import org.springframework.stereotype.Component;
import org.eirudy.shareimage.annotation.AuthCheck;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.net.http.HttpRequest;

@Aspect
@Component
public class AuthIntercept {

    @Resource
    private UserService userService;

    @Around(value = "@annotation(authCheck)")
    public Object  doIntercepter(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        //这个类的目的是拿到权限，检查一些东西

        String mustRole = authCheck.mustRole();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        User user = userService.getLoginUser(request);
        UserRoleEnum  mustRoleEnum = UserRoleEnum.getUserRoleEnumByValue(mustRole);

        //如果不需要权限，放行
        if(mustRoleEnum == null){
            joinPoint.proceed();
        }

        //以下的代码必须要权限才能通过
        UserRoleEnum userRoleEnum = UserRoleEnum.getUserRoleEnumByValue(user.getUserRole());
        if(userRoleEnum == null){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"没有权限");
        }

        if(UserRoleEnum.ADMIN.equals(mustRoleEnum) && !userRoleEnum.equals(UserRoleEnum.ADMIN) ){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"没有权限");
        }

        return joinPoint.proceed();
    }

}
